package com.example.springboot2.controller;

import com.example.springboot2.common.Result;
import com.example.springboot2.dto.LoginRequest;
import com.example.springboot2.dto.LoginResponse;
import com.example.springboot2.dto.RegisterRequest;
import com.example.springboot2.entity.User;
import com.example.springboot2.service.AuthService;
import com.example.springboot2.service.UserService;
import com.example.springboot2.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.Map;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;
    private final UserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request, HttpServletRequest httpRequest) {
        // 获取客户端IP
        String clientIp = getClientIp(httpRequest);
        request.setLoginIp(clientIp);
        
        LoginResponse response = authService.login(request);
        return Result.success("登录成功", response);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody RegisterRequest request) {
        authService.register(request);
        return Result.<Void>success("注册成功", null);
    }

    /**
     * 发送验证码
     */
    @PostMapping("/verify-code")
    public Result<Void> sendVerifyCode(@RequestBody Map<String, String> request) {
        String phone = request.get("phone");
        authService.sendVerifyCode(phone);
        return Result.<Void>success("验证码已发送", null);
    }

    /**
     * 重置密码
     */
    @PostMapping("/reset-password")
    public Result<Void> resetPassword(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        String verifyCode = request.get("verifyCode");
        
        authService.resetPassword(username, password, verifyCode);
        return Result.<Void>success("密码重置成功", null);
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public Result<Void> changePassword(@RequestBody Map<String, String> request, Authentication authentication) {
        User user = (User) authentication.getPrincipal();
        String oldPassword = request.get("oldPassword");
        String newPassword = request.get("newPassword");
        
        authService.changePassword(user.getId(), oldPassword, newPassword);
        return Result.<Void>success("密码修改成功", null);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public Result<LoginResponse.UserInfo> getUserInfo(Authentication authentication) {
        User user = (User) authentication.getPrincipal();
        
        LoginResponse.UserInfo userInfo = LoginResponse.UserInfo.builder()
                .id(user.getId())
                .username(user.getUsername())
                .name(user.getName())
                .email(user.getEmail())
                .phone(user.getPhone())
                .avatar(user.getAvatar())
                .role(user.getRole().name().toLowerCase())
                .build();
        
        return Result.success(userInfo);
    }

    /**
     * 刷新token
     */
    @PostMapping("/refresh-token")
    public Result<Map<String, String>> refreshToken(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        String newToken = authService.refreshToken(token);

        return Result.success(Map.of("token", newToken));
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("后端服务正常运行！");
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        // JWT是无状态的，客户端删除token即可
        return Result.<Void>success("退出成功", null);
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String xip = request.getHeader("X-Real-IP");
        String xfor = request.getHeader("X-Forwarded-For");
        if (xfor != null && !xfor.isEmpty() && !"unknown".equalsIgnoreCase(xfor)) {
            int index = xfor.indexOf(",");
            if (index != -1) {
                return xfor.substring(0, index);
            } else {
                return xfor;
            }
        }
        if (xip != null && !xip.isEmpty() && !"unknown".equalsIgnoreCase(xip)) {
            return xip;
        }
        return request.getRemoteAddr();
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
